package khleuven.mondzorg.db.standaloneserver;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import khleuven.mondzorg.db.DBException;
import khleuven.mondzorg.db.googlespreadsheet.Datasource;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class OnlineDatasource implements Datasource {

		public static final String LOG_TAG = "OnlineDatasource";
		
		public static final String URL = "http://u0055909.webontwerp.khleuven.be/mondzorg.definitions.get.json.php";

		/**
		 * TODO Extract connection specific details and move them towards central method
		 * TODO Decide on where to put the health checks. For now, I tend to trust the external source
		 * TODO Optimize: only download entries regarding the DestinationGroup + Language 
		 * TODO Minimize network traffic: download compressed JSON
		 * 
		 * Method to retrieve all definitions found in the online master repository.
		 */
		public JSONArray getDefinitions() throws ClientProtocolException, IOException, JSONException {
				HttpClient httpclient = new DefaultHttpClient();
				//HttpPost httppost = new HttpPost(params[0]);
				//httppost.setEntity(new UrlEncodedFormEntity(new ArrayList<NameValuePair>()));
				
				HttpGet request = new HttpGet(URL);
				
				HttpResponse response = httpclient.execute(request);
				HttpEntity entity = response.getEntity();
				InputStream is = entity.getContent();
				BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
				StringBuilder sb = new StringBuilder();
				String line = null;
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				String result=sb.toString();
				JSONArray jArray = new JSONArray(result);			
				for(int i=0;i<jArray.length();i++){
					JSONObject mondzorgEntry = jArray.getJSONObject(i);
					
					Log.i(LOG_TAG, "Entry retrieved: "+mondzorgEntry.toString());
				}
				return jArray;
		}

		@Override
		public void reloadAllEntriesFromSource() throws DBException {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void reloadAllIllustrationsFromSource() throws DBException {
			// TODO Auto-generated method stub
			
		}

	}

